package huanzhao.erp.other;

import cn.dev33.satoken.stp.StpInterface;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import huanzhao.erp.mapper.StaffMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自定义权限加载接口实现
 *
 * @author April
 * 2024/10/4 14:29
 * @version 1.0
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    private final StaffMapper staffMapper;
    public static final Cache<Long, List<String>> PERMISSION_CACHE = Caffeine.newBuilder().expireAfterWrite(7, TimeUnit.DAYS).maximumSize(1000).build();

    public StpInterfaceImpl(StaffMapper staffMapper) {
        this.staffMapper = staffMapper;
    }

    @Override
    public List<String> getPermissionList(Object loginIdObj, String loginType) {
        long loginId = Long.parseLong((String) loginIdObj);
        return PERMISSION_CACHE.get(loginId, key -> {
            String permission = staffMapper.getPermissionById(loginId);
            if (StringUtils.isBlank(permission)) {
                return List.of();
            }
            return Arrays.stream(permission.split(",")).filter(StringUtils::isNotBlank).toList();
        });
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return List.of();
    }
}
